//
//  Tools.swift
//  willdo
//
//  Created by zz on 4/3/18.
//  Copyright © 2018 will do. All rights reserved.
//

import UIKit


func getSortedName(info:[ExternalMemberModel]) -> [(key: String, value: [ExternalMemberModel])]{
    
    var dict = [String:[ExternalMemberModel]]()
    
    for contact in info {
        let firstLetter = firstWordString(str: contact.name)
        if dict[firstLetter] != nil {
            dict[firstLetter]?.append(contact)
        }else{
            dict[firstLetter] = [contact]
        }
    }
    
    let sorted = dict.sorted { ($0.key == "#") ? false : ($0.key < $1.key)}
    return sorted
}

private func firstWordString(str:String) -> String {
    let mutStr = NSMutableString(string: str)
    CFStringTransform(mutStr, nil, kCFStringTransformToLatin, false)
    let pinyinStr = mutStr.folding(options: String.CompareOptions.diacriticInsensitive, locale: Locale.current)
    let strPinyin = pinyinStr.uppercased()
    let firstString = strPinyin.prefix(1)
    
    let range = "^[A-Z]$"
    let predA = NSPredicate(format: "SELF MATCHES %@", range)
    return predA.evaluate(with: firstString) ? firstString.description : "#"
}

extension UIColor {
    convenience init(hexString: String) {
        var chars = Array(hexString)
        if (hexString.hasPrefix("#")) {
            chars = Array(hexString.dropFirst())
        }
        self.init(red:  .init(strtoul(String(chars[0...1]),nil,16))/255,
                                  green: .init(strtoul(String(chars[2...3]),nil,16))/255,
                                  blue:  .init(strtoul(String(chars[4...5]),nil,16))/255,
                                  alpha: 1)}
    }

